/* 
 * File:   server.c
 * Author: dannv
 *
 * Created on October 19, 2009, 10:31 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

#define SERV_TCP_PORT 12356
#define SIZE 1024
#define BACKLOG 5

int softerror(int);
void serve(int, struct sockaddr_in);

/*
 * Afficher l'erreur et quiter le serveur
 */
void err_stop(msg) char *msg;
{
    perror(msg);
    exit(-1);
}

/*
 * 
 */
int main(int argc, char** argv) {
 
    int sockfd;
    struct sockaddr_in serv_addr, client_addr;

    // Ouvrir un tcp socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        err_stop("Open stream socket");
    }

    // 	Liez notre adresse locale afin que le client ne peut nous l'envoyer
    bzero((char *) & serv_addr, sizeof (serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(SERV_TCP_PORT);

    if (bind(sockfd, (struct sockaddr*) & serv_addr, sizeof (serv_addr)) < 0) {
        err_stop("Bind address to socket");
    }

    // Ecouter
    if (listen(sockfd, BACKLOG) < 0) {
        err_stop("Listen");
    }

    serve(sockfd, client_addr);

    return (EXIT_SUCCESS);
}

void serve(int sockfd, struct sockaddr_in client_addr) {
    int new_fd;
    socklen_t addr_size;
    char buff[SIZE];

    for (;;) {
        addr_size = sizeof (client_addr);
        // Accepter une entrante connexion
        new_fd = accept(sockfd, (struct sockaddr *) &client_addr, (socklen_t*) & addr_size);
        if (new_fd < 0) {
            perror("Accept the connection");
            // Si l'erreur est recouvrable, essayez une fois
            if (softerror(errno))
                continue;
            else
                exit(-1);
        }

        // Recevoir ce que le client a envoyé
        int len;
        if ((len = recv(new_fd, buff, SIZE, 0)) < 0) {
            perror("Receive data");
            close(new_fd);
            continue;
        }
        
        buff[len] = '\0';
        printf("Client: %s\n", buff);
        if (strcmp(buff, "Bonjour") != 0) {
            sprintf(buff, "%s\n", "Vous devez dire 'Bonjour' !!!");
            if (send(new_fd, buff, strlen(buff), 0) != strlen(buff)) {
                perror("Send message to client");
                close(new_fd);                
            }
             continue;
        }
        int i;
        for (i = 0; i < 60; i++) {
            struct tm *tm;
            time_t now = time(0);
            tm = localtime(&now);
            sprintf(buff, "Il est %d:%d:%d !\n", tm->tm_hour, tm->tm_min, tm->tm_sec);

            len = send(new_fd, buff, strlen(buff), 0);
            if (len != strlen(buff)) {
                perror("Server: Send to client");
                break;
            }
            sleep(1);
        }
        sprintf(buff, "Au revoir %s !\n", inet_ntoa(client_addr.sin_addr));
        if (send(new_fd, buff, strlen(buff), 0) != strlen(buff)) {
            perror("Server: Send to client");
            close(new_fd);
            continue;
        }
        close(new_fd);
    }
    close(sockfd);
}

/*
 * Return 1 if error is recoverable and 0 if un recoverable
 */

int softerror(int num) {
    switch (num) {
        case EAGAIN:
        case ENOSR:
        case ENODEV:
        case ENOSPC:
        case ENOMEM:
        case ENXIO:
        case ENOBUFS:
            return 1;
        default:
            return 0;
    }
}

